from django.contrib.auth import login
from django.views import View
from apps.users.models import User
from django.http import JsonResponse, response

import re
import json


class UsernameCountView(View):
    """判断用户名是否重复注册"""

    def get(self, request, username):
        print(username)
        try:
            count = User.objects.filter(username=username).count()

        except Exception as e:
            print(e)
            return JsonResponse({'code': '15', 'errmsg': '数据异常', })
        """
        :param request: 请求对象
        :param username: 用户名
        :return: JSON
        """
        # count = User.objects.filter(username=username).count()
        print(username)
        print(count)
        return JsonResponse({'code': '1', 'errmsg': 'OK', 'count': count})
         # response


class MobileCountView(View):
    """判断手机号是否重复注册"""

    def get(self, request, mobile):
        """
        :param request: 请求对象
        :param mobile: 手机号
        :return: JSON
        """
        count = User.objects.filter(mobile=mobile).count()
        return JsonResponse({'code': 0, 'errmsg': 'OK', 'count': count})


class RegisterView(View):
    def post(self, request):
        body_byte = request.body
        data_dict = json.loads(body_byte)
        username = data_dict.get('username')
        password = data_dict.get('password')
        password2 = data_dict.get('password2')
        mobile = data_dict.get('mobile')
        sms_code = data_dict.get('sms_code')
        allow = data_dict.get('allow')
        if not all([username, password, password2, mobile, sms_code, allow]):
            return JsonResponse({'code': 400, 'errmsg': '数据上传错误'})
        if not re.match(r'^[a-zA-Z0-9_]{5,20}$', username):
            return JsonResponse({'code': 400, 'errmsg': 'username格式有误!'})
        # 判断密码是否是8-20个数字
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return JsonResponse({'code': 400, 'errmsg': 'password格式有误!'})
        # 判断两次密码是否一致
        if password != password2:
            return JsonResponse({'code': 400, 'errmsg': '两次输入不对!'})
        # 判断手机号是否合法
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code': 400, 'errmsg': 'mobile格式有误!'})
        # 判断是否勾选用户协议
        if allow != True:
            return JsonResponse({'code': 400, 'errmsg': 'allow格式有误!'})
        try:
            user = User.objects.create_user(username=username,
                                            password=password,
                                            mobile=mobile)
        except Exception as e:
            return JsonResponse({'code': 400, 'errmsg': '注册失败!'})
        login(request,user)
        return JsonResponse({'code': 0, 'errmsg': '注册成功!'})
